package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.article.feign.AdminFeign;
import com.heima.article.feign.WemediaFeign;
import com.heima.article.mapper.AutomaticMapper;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.admin.pojos.AdSensitive;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmNews;
import com.heima.article.service.AutomaticService;
import com.heima.utils.common.SensitiveWordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service

public class AutomaticServiceImpl extends ServiceImpl<AutomaticMapper, ApArticle> implements AutomaticService {

    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 文章自动审核
     * @param id
     * @return
     */
    @Override
    @Transactional
   // @GlobalTransactional
    public ResponseResult autoScanByMediaNewsId(Integer id) {
        //检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.获取文章
        ResponseResult responseResult = wemediaFeign.get(id);
        if (responseResult.getCode() != AppHttpCodeEnum.SUCCESS.getCode() || responseResult.getData() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews news = (WmNews) responseResult.getData();

        //2.判断文章的状态是否满足审核状态
        if (news.getStatus() != WmNews.Status.SUBMIT.getCode() &&
                news.getStatus() != WmNews.Status.ADMIN_SUCCESS.getCode() &&
                news.getStatus() != WmNews.Status.SUCCESS.getCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该文章可能存在一些问题，请修改后在审核");
        }
        //
            // 0 草稿  1 提交（待审核）  2 审核失败   3 人工审核 4 人工审核通过 8 审核通过（待发布） 9 已发布
            // 2.1.如果状态为1
        if (news.getStatus()==WmNews.Status.SUBMIT.getCode()){
            return submitNews(news);
        }
            //2.2.如果状态为4
        if (news.getStatus()==WmNews.Status.ADMIN_SUCCESS.getCode()){
            return reviewNews(news);
        }
            //2.3如果状态为8
        if (news.getStatus()==WmNews.Status.SUCCESS.getCode()){
            return publishNews(news);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.FAIL,"操作有误");
    }

    @Autowired
    KafkaTemplate kafkaTemplate;
    /**
     * 如果状态为8
     * @param news
     * @return
     */
    private ResponseResult publishNews(WmNews news) {
        //判断发布时间小于等于当前时间，则发布
        if (news.getPublishTime().getTime()<=(new Date()).getTime()){
            news.setStatus(WmNews.Status.PUBLISHED.getCode());
            saveArticle(news);

        }
        return null;
    }

    @Autowired
    GreeTextScan greeTextScan;
    @Autowired
    GreenImageScan greenImageScan;

    @Autowired
    FastDFSClient fastDFSClient;

    @Autowired
    AdminFeign adminFeign;



    /**
     * 状态为4
     * @param news
     * @return
     */
    private ResponseResult reviewNews(WmNews news) {
        //判断发布时间小于等于当前时间，则发布
        if (news.getPublishTime().getTime()<=(new Date()).getTime()){
            news.setStatus(WmNews.Status.PUBLISHED.getCode());
            saveArticle(news);
        }else {
            news.setStatus(WmNews.Status.SUCCESS.getCode());
            news.setReason("待发布");
            wemediaFeign.updateWmNews(news);
            return ResponseResult.errorResult(AppHttpCodeEnum.FAIL,"待发布");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 1 提交（待审核）
     * @param news
     * @return
     */
    private ResponseResult submitNews(WmNews news) {
        //1.获取文本信息
        //1.1获取图片信息,并进行安全验证
        Map<String, String> map1 = getImg(news);
        //1.2获取文本信息并文本校验
        Map<String, String> map = getText(news);
        if ("block".equals(map1.get("suggestion"))||"block".equals(map.get("suggestion"))){
            news.setStatus(WmNews.Status.FAIL.getCode());
            news.setReason("存在不良信息，请更正后在提交");
            wemediaFeign.updateWmNews(news);
           return ResponseResult.errorResult(AppHttpCodeEnum.FAIL,"存在不良信息，请更正后在提交");
        }

        if ("review".equals(map1.get("suggestion"))||"review".equals(map.get("suggestion"))){
            //修改状态为人工审核
            news.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
            news.setReason("需要人工审核");
            wemediaFeign.updateWmNews(news);
            return ResponseResult.errorResult(AppHttpCodeEnum.FAIL,"需要人工审核");
        }
        if ("pass".equals(map1.get("suggestion"))||"pass".equals(map.get("suggestion"))){
            //判断发布时间小于等于当前时间，则发布
            if (news.getPublishTime().getTime()<=(new Date()).getTime()){
                news.setStatus(WmNews.Status.PUBLISHED.getCode());
                saveArticle(news);
            }else {
                news.setStatus(WmNews.Status.SUCCESS.getCode());
                news.setReason("待发布");
                wemediaFeign.updateWmNews(news);
                return ResponseResult.errorResult(AppHttpCodeEnum.FAIL,"待发布");
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    ApArticleConfigServiceImpl articleConfigService;

    @Autowired
    ApArticleContentServiceImpl articleContentService;

    @Autowired
    ApArticleServiceImpl articleService;

    @Autowired
    AuthorServiceImpl authorService;

    //@Autowired
    //RestHighLevelClient restHighLevelClient;
    //保存文章信息ApArticle, ApArticleConfig  ApArticleContent
    private void saveArticle(WmNews news) {
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getUserId, news.getUserId()));

        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(news.getTitle());
        apArticle.setLayout(news.getType());
        apArticle.setImages(news.getImages());
        apArticle.setCreatedTime(new Date());

        //获取作者相关信息
            if(apAuthor != null){
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }

        //获取频道相关信息
        ResponseResult<AdChannel> result = adminFeign.findById(news.getChannelId());
        AdChannel channel = result.getData();
        if(channel != null){
            apArticle.setChannelId(channel.getId());
            apArticle.setChannelName(channel.getName());
        }
        saveOrUpdate(apArticle);
        saveArticleConfig(apArticle);
        saveArticleContent(apArticle,news);

        //文章发布成则更新到ElasticSearch中
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", apArticle.getId());
        map.put("publishTime", apArticle.getPublishTime());
        map.put("layout", apArticle.getLayout());
        map.put("images", apArticle.getImages());
        map.put("authorId", apArticle.getAuthorId());
        map.put("title", apArticle.getTitle());

      /*  try {
            IndexRequest request=new IndexRequest("app_info_article").id(apArticle.getId().toString()).source(map);
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //如果保存成功则保存文章修改状态
        wemediaFeign.updateWmNews(news);

    }
    /**
     * 创建app端文章内容信息
     * @param apArticle
     * @param wmNews
     */
    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleContentService .save(apArticleContent);

    }

    /**
     * 创建app端文章配置信息
     * @param apArticle
     */
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);

        articleConfigService.save(apArticleConfig);
    }

    //获取图片信息,并进行安全验证
    private  Map<String,String> getImg(WmNews news) {
        HashSet<String> set=new HashSet<>(); //利用set去除重复图片
        //获取内容图片
        String content = news.getContent();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if ( "image".equals(map.get("type"))){
                String[] values = map.get("value").toString().split(",");
                set.addAll(Arrays.asList(values));
            }
        }
        //获取标题图片
        String images = news.getImages();
        String[] split = images.split(",");
        set.addAll(Arrays.asList(split));

        ArrayList<byte[]> list=new ArrayList<>();
        //根据图片路径获取图片
        if (set.size()>0){
            for (String s : set) {
                String group = s.substring(0, s.indexOf("/"));
                String url = s.substring(s.indexOf("/") + 1);
                try {
                    byte[] bytes = fastDFSClient.download(group, url);
                    list.add(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException("fastDFS下载图片异常");
                }
            }
        }
        Map<String,String> map=new HashMap();
        try {
             map = greenImageScan.imageScan(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("图片校验出现异常");
        }

        return map;
    }

    /**
     * 获取文本信息
     * @param news
     * @return
     */
    private  Map<String,String> getText(WmNews news) {
        HashSet<String> set=new HashSet<>(); //利用set去除重复文件
        //获取内容
        String content = news.getContent();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if ( "text".equals(map.get("type"))){
                set.add(map.get("value").toString());
            }
        }
        Map<String,String> map=new HashMap();
        try {
             map = greeTextScan.greeTextScan(Arrays.toString(set.toArray()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件校验出现异常");
        }
        //2对敏感词进行校验
        //2.1从数据库获取敏感词
        ResponseResult<List<AdSensitive>> result = adminFeign.findAll();
        if (result.getCode()==AppHttpCodeEnum.SUCCESS.getCode()){
            List<AdSensitive> sensitiveList = result.getData();
            ArrayList<String> arrayList=new ArrayList<>();
            for (AdSensitive sensitive : sensitiveList) {
                arrayList.add(sensitive.getSensitives());
            }
            SensitiveWordUtil.initMap(arrayList);

            Map<String, Integer> wordsmap = SensitiveWordUtil.matchWords(set.toString());
            //如果wordsmap有值说名出现了敏感词，则不能通过
            if (wordsmap.size()>0){
                throw new RuntimeException("存在敏感词："+wordsmap.toString());
            }
        }
        return map;
    }

}
